/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.ruralLibrary.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.ruralLibrary.api.entity.ResourceEntity;
import com.pig4cloud.pigx.ruralLibrary.api.vo.ArticleCatalogVo;
import com.pig4cloud.pigx.ruralLibrary.service.ResourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 资源
 *
 * @author pig
 * @date 2023-10-31 14:34:33
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/resource")
@Tag(description = "resource", name = "资源管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ResourceController {

	private final ResourceService resourceService;

	/**
	 * 分页查询
	 *
	 * @param page     分页对象
	 * @param resource 资源
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('ruralLibrary_resource_view')")
	public R getresourcePage(Page page, ResourceEntity resource) {
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(resource.getResourceName()), ResourceEntity::getResourceName, resource.getResourceName());
		wrapper.like(StrUtil.isNotBlank(resource.getAuthor()), ResourceEntity::getAuthor, resource.getAuthor());
		wrapper.like(StrUtil.isNotBlank(resource.getPress()), ResourceEntity::getPress, resource.getPress());
		wrapper.eq(resource.getBookTypeId() != null, ResourceEntity::getBookTypeId, resource.getBookTypeId());
		wrapper.eq(resource.getDataTypeId() != null, ResourceEntity::getDataTypeId, resource.getDataTypeId());
		wrapper.ne(ResourceEntity::getResourceId, 0);
		return resourceService.pageList(page, wrapper);
	}


	/**
	 * 通过id查询资源
	 *
	 * @param resourceId id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询")
	@GetMapping("/{resourceId}")
	@PreAuthorize("@pms.hasPermission('ruralLibrary_resource_view')")
	public R getById(@PathVariable("resourceId") Long resourceId) {
		return R.ok(resourceService.getById(resourceId));
	}

	/**
	 * 新增资源
	 *
	 * @return R
	 */
	@Operation(summary = "新增资源", description = "新增资源")
	@SysLog("新增资源")
	@PostMapping
	public R save() {
		return resourceService.saveAll();
	}

	/**
	 * 修改资源
	 *
	 * @param resource 资源
	 * @return R
	 */
	@Operation(summary = "修改资源", description = "修改资源")
	@SysLog("修改资源")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('ruralLibrary_resource_edit')")
	public R updateById(@RequestBody ResourceEntity resource) {
		return R.ok(resourceService.updateById(resource));
	}

	/**
	 * 通过id删除资源
	 *
	 * @param ids resourceId列表
	 * @return R
	 */
	@Operation(summary = "通过id删除资源", description = "通过id删除资源")
	@SysLog("通过id删除资源")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('ruralLibrary_resource_del')")
	public R removeById(@RequestBody Long[] ids) {
		return R.ok(resourceService.removeBatchByIds(CollUtil.toList(ids)));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param resource 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('ruralLibrary_resource_export')")
	public List<ResourceEntity> export(ResourceEntity resource) {
		return resourceService.list(Wrappers.query(resource));
	}

	@GetMapping("/pageView/{resourceId}")
	@Inner(value = false)
	public void pageView(@PathVariable("resourceId") Long resourceId) {
		resourceService.pageView(resourceId);
	}

	@GetMapping(value = "/getProductResourcesDetails/{resourceId}")
	@Inner(value = false)
	public R getProductResourcesDetails(@PathVariable("resourceId") String resourceId, HttpServletResponse response) {
		response.setHeader("Accept-Ranges","bytes");
		return resourceService.getProductResourcesDetails(resourceId);
	}


	@Inner(value = false)
	@PostMapping("/search")
	public R search(@RequestBody String search) {
		return resourceService.search(search);
	}
	@Inner(value = false)
	@GetMapping ("/search")
	public R searchTo(String search) {
		return resourceService.search(search);
	}

	@GetMapping("/getBookDataType/{dataTypeId}")
	@Inner(value = false)
	public R getBookDataType(@PathVariable("dataTypeId") String dataTypeId, @ParameterObject Page page) {
		if (dataTypeId == null) {
			return R.failed("数据异常，请联系管理员");
		}
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ResourceEntity::getDataTypeId, dataTypeId);
		wrapper.ne(ResourceEntity::getCover, "http://61.163.243.7:9999/digitallibrary/file/lengleng/暂无封面.jpg");
		wrapper.orderByDesc(ResourceEntity::getCreateTime);
		return R.ok(resourceService.page(page,wrapper));
	}

	@GetMapping("/getBookDataType/getPageView/{dataTypeId}")
	@Inner(value = false)
	public R getBookDataTypePageView(@PathVariable("dataTypeId") String dataTypeId, @ParameterObject Page page) {
		if (dataTypeId == null) {
			return R.failed("数据异常，请联系管理员");
		}
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ResourceEntity::getDataTypeId, dataTypeId);
		wrapper.orderByDesc(ResourceEntity::getPageView);
		return R.ok(resourceService.page(page,wrapper));
	}

	@PostMapping("/getBookType")
	@Inner(value = false)
	public R getBookType(@RequestBody ResourceEntity resource) {
		if (resource.getDataTypeId() == null) {
			return R.failed("数据异常，请联系管理员");
		}
		if (resource.getBookTypeId() == null) {
			return R.failed("数据异常，请联系管理员");
		}
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ResourceEntity::getDataTypeId, resource.getDataTypeId());
		wrapper.eq(ResourceEntity::getBookTypeId, resource.getBookTypeId());
		wrapper.orderByDesc(ResourceEntity::getCreateTime);
		return R.ok(resourceService.page(resource.getPage(),wrapper));
	}

	@PostMapping("/getBookType/getPageView")
	@Inner(value = false)
	public R getBookTypePageView(@RequestBody ResourceEntity resource) {
		if (resource.getDataTypeId() == null) {
			return R.failed("数据异常，请联系管理员");
		}
		if (resource.getBookTypeId() == null) {
			return R.failed("数据异常，请联系管理员");
		}
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ResourceEntity::getDataTypeId, resource.getDataTypeId());
		wrapper.eq(ResourceEntity::getBookTypeId, resource.getBookTypeId());
		wrapper.orderByDesc(ResourceEntity::getPageView);
		return R.ok(resourceService.list(wrapper));
	}

	@GetMapping("/books/{id}")
	@Inner(value = false)
	public R books(@PathVariable("id") Long id) {
		return resourceService.books(id);
	}

	@GetMapping("/video/{id}")
	@Inner(value = false)
	public R video(@PathVariable("id") Long id) {
		return resourceService.video(id);
	}

	@GetMapping("/audio/{id}")
	@Inner(value = false)
	public R audio(@PathVariable("id") Long id) {
		return resourceService.audio(id);
	}

	@GetMapping("/periodical/{id}")
	@Inner(value = false)
	public R periodical(@PathVariable("id") Long id) {
		return resourceService.periodical(id);
	}


	@GetMapping(value = "/particularsBooks/{ids}")
	@Inner(value = false)
	public R particularsBooks(@PathVariable("ids") String ids) {
		return resourceService.particularsBooks(ids);
	}


	@PostMapping("/getJournalSearchResult")
	@Inner(value = false)
	public R getJournalSearchResult(@RequestBody Map<String, Object> body) {
		String searchKeywords = (String) body.get("searchKeywords");
		return resourceService.getJournalSearchResult(searchKeywords);
	}

	@PostMapping("/getJournalSearchResultWXMini")
	@Inner(value = false)
	public R getJournalSearchResultWXMini(@RequestBody Map<String, String> map) {
		String s = map.get("searchKeywords");
		return resourceService.getJournalSearchResult(s);
	}

	@PostMapping("/getArticleCatalog")
	@Inner(value = false)
	public R getArticleCatalog(ArticleCatalogVo articleCatalogVo) {
		return resourceService.getArticleCatalog(articleCatalogVo);
	}

	@PostMapping("/getArticleCatalogWxMini")
	@Inner(value = false)
	public R getArticleCatalogWxMini(@RequestBody ArticleCatalogVo articleCatalogVo) {
		return resourceService.getArticleCatalog(articleCatalogVo);
	}

	@GetMapping("/getArticleDetail/{id}")
	@Inner(value = false)
	public R getArticleDetail(@PathVariable("id") String id) {
		return resourceService.getArticleDetail(id);
	}

}
